﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;

namespace Commute.Model
{
    public class ModelLoader
    {
        public Timetable LoadTimetable( string path )
        {
            var timetable = new Timetable();
            var document = System.Xml.Linq.XDocument.Load( path );

            foreach ( var service in document.Descendants( "Stop" ) )
            {
                var newStop = new Stop() { Name = service.Attribute( "Name" ).Value, Description = service.Attribute( "Description" ).Value };
                timetable.Stops.Add( newStop.Name, newStop );
            }

            foreach ( var service in document.Descendants( "Service" ) )
            {
                var newService = new Service() { Name = service.Attribute( "Name" ).Value };

                foreach ( var route in service.Descendants( "Route" ) )
                {
                    var newRoute = new Route() { Name = route.Attribute( "Name" ).Value, Description = route.Attribute( "Description" ).Value };

                    foreach ( var runStop in route.Descendants( "Run" ) )
                    {
                        var newRun = new Run();

                        foreach ( var run in runStop.Descendants( "RunStop" ) )
                        {
                            var newRunStop = new RunStop { Stop = timetable.Stops[ run.Attribute( "Stop" ).Value ], Time = XmlConvert.ToDateTime( "2008-01-01T" + run.Attribute( "Time" ).Value + ":00", XmlDateTimeSerializationMode.Local ) };
                            newRun.Stops.Add( newRunStop );
                        }

                        newRoute.Runs.Add( newRun );
                    }

                    newService.Routes.Add( newRoute );
                }

                timetable.Services.Add( newService );
            }

            return timetable;
        }
    }
}
